import os

from django.core.files.base import ContentFile
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from datetime import datetime

from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill

from accounts.mugshot import Avatar


def user_mugshot_path(instance, filename):
    """
    设置用户头像存储路径
    :param instance:
    :param filename:
    :return:
    """
    return os.path.join('mugshots', instance.username, filename)


class UserProfile(AbstractUser):
    """
    重写django的user
    """

    nick_name = models.CharField(max_length=50, verbose_name=_('nick_name'), default='')
    birthday = models.DateField(null=True, blank=True, verbose_name=_('birthday'))
    gender = models.CharField(max_length=6, choices=(('male', _('male')), ('female', _('female'))), default='male',
                              verbose_name=_('gender'))
    address = models.CharField(max_length=100, default='', verbose_name=_('address'))
    mobile = models.CharField(max_length=11, null=True, blank=True, verbose_name=_('mobile'))
    mugshot = models.ImageField(upload_to=user_mugshot_path, verbose_name=_('mugshot'))
    mugshot_thumbnail = ImageSpecField(source='mugshot', processors=[ResizeToFill(96, 96)],
                                       format='JPEG',
                                       options={'quality': 80})

    def save(self, *args, **kwargs):
        if not self.nick_name:
            self.nick_name = self.username

        if not self.mugshot:
            """
            如果用户没有上传头像,则随机生成一个用户的头像
            """
            avatar = Avatar(rows=10, columns=10)
            image_byte_array = avatar.get_image(string=self.username,
                                                width=480,
                                                height=480,
                                                pad=10)
            self.mugshot.save('default_mugshot.png', ContentFile(image_byte_array), save=True)
        super().save(*args, **kwargs)

    class Meta:
        verbose_name = _('user_profile')
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username


class EmailVerifyRecord(models.Model):
    """
    用于处理邮箱验证码
    """
    code = models.CharField(max_length=20, verbose_name=_('identifying_code'))
    email = models.EmailField(max_length=50, verbose_name=_('email'))
    send_type = models.CharField(max_length=18, choices=(('register', _('email_register')),
                                                         ('forget', _('forget_password')),
                                                         ('update_email', _('update_email'))),
                                 verbose_name=_('identifying_code_type'))
    send_time = models.DateField(default=datetime.now, verbose_name=_('send_time'))

    class Meta:
        verbose_name = _('email_identifying_code')
        verbose_name_plural = verbose_name


class UserMessage(models.Model):
    # 如果 为 0 代表全局消息，否则就是用户的 ID
    user = models.IntegerField(default=0, verbose_name=_('receive_user'))
    message = models.CharField(max_length=500, verbose_name=_('message_content'))
    has_read = models.BooleanField(default=False, verbose_name=_('is_read'))
    add_time = models.DateTimeField(default=datetime.now, verbose_name=_('add_time'))

    class Meta:
        verbose_name = _('user_message')
        verbose_name_plural = verbose_name
